# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2023-1-10 18:04
# @file : send.py
import os
import smtplib
import time
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import zipfile


class SendEmail:
    """发送邮件"""

    def __init__(self, host, user, password, port=465):
        """
        :param host: 邮箱服务
        :param port: 端口号
        :param user: 邮箱
        :param password: 邮箱授权码
        """
        if port == 465 or port == 587:
            self.smtp = smtplib.SMTP_SSL(host=host, port=port)
        else:
            self.smtp = smtplib.SMTP(host=host, port=port)
        self.smtp.login(user=user, password=password)
        self.user = user

    def send_email(self, subject="test report", content=None, filename=None, to_addrs=None):
        """
        :param subject:邮件主题
        :param content: 邮件正文
        :param filename: 附件
        :param to_addrs: 发送人地址
        :type to_addrs: 字符串或列表
        :return:
        """
        msg = MIMEMultipart()
        msg["Subject"] = subject
        msg["From"] = self.user
        if isinstance(to_addrs, str):
            msg["To"] = to_addrs
        elif to_addrs and isinstance(to_addrs, list):
            msg["To"] = to_addrs[0]
        if not content:
            content = time.strftime("%Y-%m-%d-%H_%M_%S") + ":测试报告"
        text = MIMEText(content, _subtype="html", _charset="utf8")
        msg.attach(text)
        if filename and os.path.isfile(filename):
            with open(filename, "rb") as f:
                content = f.read()
            try:
                report = MIMEApplication(content, _subtype=None)
            except:
                report = MIMEApplication(content, _charset="utf8")
            name = os.path.split(filename)[1]
            report.add_header('content-disposition', 'attachment', filename=name)
            msg.attach(report)
        try:
            self.smtp.send_message(msg, from_addr=self.user, to_addrs=to_addrs)
        except Exception as e:
            print("报告发送失败")
            raise e
        else:
            print("报告发送成功")

    def zipDir(self, outFullName, dirpath):
        zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dirpath):
            # 去掉目标跟路径，只对目标文件夹下边的文件及文件夹进行压缩
            fpath = path.replace(dirpath, '')

            for filename in filenames:
                zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
        zip.close()
        print('压缩成功')


if __name__ == '__main__':
    pass
